import { Injectable } from "@angular/core";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { LayersService } from "../../services";
import { LayersActionTypes, LoadLayerSuccess, LoadLayerFail, LoadLayer, InitialLayersFail, InitialLayersSuccess } from "../actions/layers.action";
import { switchMap, map, catchError } from "rxjs/operators";
import { Layer } from "../../class";
import { of } from "rxjs/observable/of";



@Injectable()
export class LayersEffect {

    constructor(
        private action$: Actions,
        private api: LayersService
    ) {}

    @Effect()
    InitialLayers$ = this.action$.pipe(
        ofType(LayersActionTypes.INITIAL_LAYERS),
        switchMap(() => {
            return this.api.getDefaultlayers().pipe(
                map((layers: Layer[]) => new InitialLayersSuccess(layers)),
                catchError(error => of(new InitialLayersFail(error)))
            );
        })
    );

    @Effect()
    LoadLayer$ = this.action$.pipe(
        ofType(LayersActionTypes.LOAD_LAYER),
        switchMap((action: LoadLayer) => {
            return this.api.getLayers(action.payload).pipe(
                map((layer: Layer[]) => new LoadLayerSuccess(layer)),
                catchError(error => of(new LoadLayerFail(error)))
            );
        })
    );

}